#!/bin/python

### ### ### ### ### ### ### ### ### ### ### ### ### ### ### 
#   arguments:
#             input_file(\n separated list of packages)
#             out_dir -- default is .
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### 

import sys, os

inFile = sys.argv[1]

buf = open(inFile).read();
pkgnames = buf.split("\n")

debs = set()

for pkg in pkgnames:
    if len(pkg) == 0:
        continue
    os.system("apt-get install --print-uris --assume-yes -y " + pkg + " > /tmp/create-pkgs-tmp")
    buf = open("/tmp/create-pkgs-tmp").read();
    added = 0
    for debdef in buf.split("\n"):
        if debdef.startswith("'"):
            debdef = debdef[1:]
            debdef = debdef[:debdef.index("'")]
            debs.add(debdef)
            added += 1
    if added == 0:
        print "Warning: pkg\n\t" + pkg + "\nno debs found"
        
debsl = []
debsl.extend(debs)
debsl.sort()

outdir = "."
if len(sys.argv) > 2:
    outdir = sys.argv[2]
if not os.path.exists(outdir):
    os.makedirs(outdir)
outf = open(os.path.join(outdir, "download"), "w")
outf.write("#!/bin/bash\n")
if not os.path.exists("/local-repository"):
    outf.write("mkdir /local-repository\n")
outf.write("mount --bind . /local-repository\n")
outf.write("cd /local-repository\n")
for deb in debsl:
    outf.write("wget " + deb + "\n")
outf.close()
os.system("chmod a+x " + os.path.join(outdir, "download"))

outf = open(os.path.join(outdir, "localrep"), "w")
outf.write("#!/bin/bash\n")
outf.write("cd /local-repository\n")
pkgDir = os.path.join(outdir, "dists", "main", "main", "binary-i386")
if not os.path.exists(pkgDir):
    os.makedirs(pkgDir)
#outf.write("mkdir dists/main/main/binary-i386\n")
pkgFile = os.path.join("/local-repository", "dists", "main", "main", "binary-i386", "Packages.gz")
outf.write("dpkg-scanpackages . /dev/null | gzip -9c > " + pkgFile + "\n")
outf.close()
os.system("chmod a+x " + os.path.join(outdir, "localrep"))
